﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using ISC.MapDotNetServer.Common.Maps;
using ISC.MapDotNetServer.Common.WMS;
using ISC.RIM.Silverlight;
using OI.Framework;

namespace OI.ViewModels
{
    public class FeedLinksViewModel : Screen
    {
        #region DATA
        public List<Layer> Layers { get; private set; }
        public List<string> LayerIDs
        {
            get
            {
                return Layers.Select(l => l.ID).ToList();
            }
        }
        public Envelope Extents { get; private set; }
        private const int SampleWidth = 500;

        public string WMSLink
        {
            get
            {
                var wmsClient = new WMSClient(
                    Configuration.GetBaseURI() + 
                    Configuration.OGCEndpoint +
                    "WMS.ashx", 
                    WMSClient.Versions.V1_3);

                string endpoint = wmsClient.GetMapURL(
                    LayerIDs,
                    Framework.Utility.SphericalMercatorCoordSys,
                    Extents,
                    SampleWidth,
                    GetHeight(Extents, SampleWidth),
                    "image/png",
                    false,
                    Configuration.Jurisdiction.MashupMapID);

                return endpoint;
            }
        }


        public string RESTLink
        {
            get
            {
                string extStr = string.Format("{0},{1},{2},{3}", Extents.UL.X, Extents.UL.Y, Extents.LR.X, Extents.LR.Y);
                var layVisStr = new StringBuilder();
                foreach (var id in LayerIDs)
                {
                    layVisStr.Append(id + ",1,");
                }

                string sizeStr = SampleWidth + "," + GetHeight(Extents, SampleWidth);

                string endpoint = Configuration.GetBaseURI() +
                    Configuration.RESTEndpoint +
                    Configuration.Jurisdiction.MashupMapID +
                    "/Image/Extent/" +
                    extStr +
                    "/" + sizeStr + "/?LayerVisibility=" +
                    layVisStr.ToString().Trim(',');

                return endpoint;
            }
        }


        public string RESTLinkQuad
        {
            get
            {
                // get the zoom level for fitting the extents in a sample quad tile
                double zl = Framework.Utility.SphericalMercatorProj.GetBestFitZoomLevelByExtents(Extents, new Envelope(0, 0, SampleWidth, SampleWidth));

                // get a set of quadtiles based on extents and zl
                var qts = Framework.Utility.SphericalMercatorProj.GetQuadTreeNodesInEnvelope(Extents, Convert.ToInt32(Math.Ceiling(zl)));
                if (qts.Count > 0)
                {
                    // find quad-key in center
                    int idx = qts.TakeWhile(qt => !Framework.Utility.SphericalMercatorProj.GetTileEnvelope(qt.Key).Contains(Extents.Center)).Count();

                    var layVisStr = new StringBuilder();
                    foreach (var id in LayerIDs)
                    {
                        layVisStr.Append(id + ",1,");
                    }

                    string sizeStr = SampleWidth + "," + SampleWidth;

                    string endpoint = Configuration.GetBaseURI() +
                        Configuration.RESTEndpoint +
                        Configuration.Jurisdiction.MashupMapID +
                        "/Image/Qkey/" +
                        qts[idx].Key +
                        "/" + sizeStr + "/?LayerVisibility=" +
                        layVisStr.ToString().Trim(',');

                    return endpoint;
                }
                return "";
            }
        }


        public string GeoRSSHeader
        {
            get
            {
                var geoRSSLayer = Layers.FirstOrDefault(l => l.HasRSSEnable());
                if (geoRSSLayer != null)
                {
                    return "GeoRSS: " + geoRSSLayer.GetLayerName(geoRSSLayer.ID);
                }
                return "GeoRSS not enabled";
            }
        }


        public string GeoRSSLinkUri
        {
            get
            {
                var geoRSSLayer = Layers.FirstOrDefault(l => l.HasRSSEnable());
                if (geoRSSLayer != null)
                {
                    string endpoint =
                       Configuration.GetBaseURI() +
                       Configuration.RSSEndpoint +
                       "?MapID=" +
                       Configuration.Jurisdiction.MashupMapID +
                       "&LayerID=" +
                       geoRSSLayer.ID;

                    return endpoint;
                }
                return "";
            }
        }



        public string ODataLink
        {
            get
            {
                string endpoint = Configuration.ODATAEndpoint + ((Layers.Count == 1) ? Layers[0].ConnectionSpecification.DataTable : "");
                return endpoint;
            }
        }


        #endregion


        public FeedLinksViewModel(List<Layer> layers, Envelope extents)
        {
            Layers = layers;
            Extents = extents;
            base.DisplayName = "Feeds";
        }


        public void Close()
        {
            TryClose();
        }


        // returns appropriate width given the map extent and supplied width
        private static int GetHeight(Envelope extent, int width)
        {
            return Convert.ToInt32(width / extent.AspectRatio);
        }

    }
}
